/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.controller;

import com.alibaba.fastjson.JSONObject;
import com.legendshop.dao.support.PageSupport;
import com.legendshop.framework.controller.BaseController;
import com.legendshop.oa.constants.ApplicationEnum;
import com.legendshop.oa.constants.FunctionEnum;
import com.legendshop.oa.constants.PathResolver;
import com.legendshop.oa.model.AdminUser;
import com.legendshop.oa.model.AdminUserPassword;
import com.legendshop.oa.model.Role;
import com.legendshop.oa.pages.AdminTilesPage;
import com.legendshop.oa.pages.BackPage;
import com.legendshop.oa.pages.RedirectPage;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.security.UserManager;
import com.legendshop.oa.service.DepartmentService;
import com.legendshop.oa.util.MD5Util;
import com.legendshop.oa.util.PageSupportHelper;
import com.legendshop.permission.service.AdminUserService;
import com.legendshop.util.AppUtils;
import com.legendshop.util.LogDateUtil;
import com.legendshop.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

/**
 * 管理员控制器
 *
 */
@Controller
@RequestMapping("/admin/adminUser")
public class AdminUserController extends BaseController {
	@Autowired
	private AdminUserService adminUserService;

	@Autowired
	private DepartmentService departmentService;

	/**
	 * 检查管理员是否存在
	 * 
	 * @param userName
	 * @return
	 */
	@RequestMapping("/isAdminUserExist")
	public @ResponseBody Boolean isUserExist(String userName) {
		if (AppUtils.isBlank(userName)) {
			return true;// 用户名不允许有空值
		}
		boolean result = adminUserService.isAdminUserExist(userName.trim());
		return result;
	}

	/**
	 * 查询用户列表
	 */
	@RequestMapping("/query")
	public String query(HttpServletRequest request, HttpServletResponse response, String curPageNO, AdminUser adminUser) {
		PageSupport<AdminUser> ps = adminUserService.getAdminUser(curPageNO, adminUser);
		
		//查询每个周报
		PageSupportHelper.savePage(request, ps);
		request.setAttribute("bean", adminUser);

		return PathResolver.getPath(request, response, AdminTilesPage.ADMINUSER_LIST_PAGE);
	}

	/**
	 * 保存管理员
	 */
	@RequestMapping(value = "/save")
	public String save(HttpServletRequest request, HttpServletResponse response, AdminUser adminUser) {
		// 加密密码
		adminUser.setPassword(MD5Util.toMD5Password(adminUser.getName(), adminUser.getPassword()));
		Date date = new Date();
		adminUser.setRecDate(date);
		adminUser.setModifyDate(date);
		adminUser.setNeedDailyLog(1);////是否需要填写日志
		adminUser.setPassChangeDate(LogDateUtil.getPasswordChangeDate());//下次更改密码的时间
		adminUserService.saveAdminUser(adminUser);
		saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("operation.successful"));
		return PathResolver.getPath(request, response, RedirectPage.ADMINUSER_LIST_QUERY);
	}

	/**
	 * 删除管理员
	 */
	@RequestMapping(value = "/delete/{id}")
	public String delete(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
		AdminUser adminUser = adminUserService.getAdminUser(id);
		adminUserService.deleteAdminUser(adminUser);
		saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("entity.deleted"));
		return PathResolver.getPath(request, response, RedirectPage.ADMINUSER_LIST_QUERY);
	}

	/**
	 * 根据Id加载
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/load/{id}")
	public String load(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
		AdminUser adminUser = adminUserService.getAdminUser(id);
		request.setAttribute("adminUser", adminUser);
		if (adminUser.getDeptId() != null) {
			String deptName = departmentService.getDepartmentName(adminUser.getDeptId());
			request.setAttribute("deptName", deptName);
		}

		if(adminUser.getLeader() != null){
			AdminUser leader = adminUserService.getAdminUserByUserName(adminUser.getLeader());
			if(leader != null){
				request.setAttribute("leaderName", leader.getRealName());
			}
		}

		return PathResolver.getPath(request, response, AdminTilesPage.ADMINUSER_UPDATE_PAGE);
	}

	/**
	 * 加载管理员编辑
	 */
	@RequestMapping(value = "/load")
	public String load(HttpServletRequest request, HttpServletResponse response) {
		List<Role> roleList;
		// 判断是否有VIEW_ALL_DATA权限，如果有，则加载所有的权限
		if (UserManager.hasFunction(request, FunctionEnum.FUNCTION_VIEW_ALL_DATA.value())) {
			roleList = adminUserService.loadRole(ApplicationEnum.BACK_END.value());
		} else {
			// 如果没有权限则只可以给自己范围内的权限
			roleList = adminUserService.loadRole(UserManager.getUserId(request), ApplicationEnum.BACK_END.value());
		}

		//排除掉系统管理的角色
		List<Role> roles = roleList.stream().filter(role -> role.getCategory() == 2).collect(Collectors.toList());

		request.setAttribute("roleList", roles);
		return PathResolver.getPath(request, response, AdminTilesPage.ADMINUSER_EDIT_PAGE);
	}

	/**
	 * 更新管理员信息
	 */
	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public String update(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
		AdminUser adminUser = adminUserService.getAdminUser(id);
		request.setAttribute("adminUser", adminUser);
		return PathResolver.getPath(request, response, RedirectPage.ADMINUSER_LIST_QUERY);
	}

	/**
	 * 更新管理员的密码
	 * @param request
	 * @param response
	 * @param adminUser
	 * @return
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String updateAdminUser(HttpServletRequest request, HttpServletResponse response, AdminUser adminUser) {
		AdminUser orgin = adminUserService.getAdminUser(adminUser.getId());
		if (orgin != null) {
			orgin.setEnabled(adminUser.getEnabled());
			orgin.setNote(adminUser.getNote());
			orgin.setDeptId(adminUser.getDeptId());
			orgin.setRealName(adminUser.getRealName());
			orgin.setHireDate(adminUser.getHireDate());
			orgin.setIdCardNum(adminUser.getIdCardNum());
			orgin.setAddr(adminUser.getAddr());
			orgin.setMobile(adminUser.getMobile());
			orgin.setActiveTime(adminUser.getActiveTime());
			orgin.setLeader(adminUser.getLeader());//上级
			orgin.setPosition(adminUser.getPosition());
			orgin.setSex(adminUser.getSex());
			orgin.setNeedDailyLog(adminUser.getNeedDailyLog());
			orgin.setChangePass(adminUser.getChangePass());
			adminUserService.updateAdminUser(orgin);
			saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("operation.successful"));
		} else {
			saveError(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("operation.error"));
		}
		return PathResolver.getPath(request, response, RedirectPage.ADMINUSER_LIST_QUERY);
	}

	/**
	 * 加载更新管理员密码页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updatePwd", method = RequestMethod.GET)
	public String loadUpdatePassword(HttpServletRequest request, HttpServletResponse response) {
		AdminUser adminUser = adminUserService.getAdminUser(UserManager.getUserId(request));
		request.setAttribute("adminUser", adminUser);
		return PathResolver.getPath(request, response, BackPage.UPDATE_ADMIN_PWD);
	}

	/**
	 * 更新管理员密码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/updatePwd", method = RequestMethod.POST)
	@ResponseBody
	public String updatePassword(HttpServletRequest request, HttpServletResponse response, AdminUserPassword userPassword) {

		if(!PasswordUtil.isPasswordOK(userPassword.getPassword())){
			//太简单
			return "TOSIMPLE";
		}


		AdminUser orgin = adminUserService.getAdminUser(userPassword.getId());
		if (orgin != null) {
			// check password
			String oldEnCryptPasswd = MD5Util.toMD5Password(orgin.getName(), userPassword.getOldPassword());
			if (oldEnCryptPasswd.equals(orgin.getPassword())) {
				String newEnCryptPasswd = MD5Util.toMD5Password(orgin.getName(), userPassword.getPassword());
				if (!oldEnCryptPasswd.equals(newEnCryptPasswd)) {// 密码不相等才修改
					orgin.setPassword(newEnCryptPasswd);
					adminUserService.updateAdminUser(orgin);
					return "OK"; // 修改成功
				} else {
					return "NOCHANGE";// 没有改密码
				}

			} else {
				return "DISMATCH";// 原来密码不匹配
			}
		} else {
			return "NOTFOUND"; // 找不到记录
		}
	}
	
	/**
	 * 查询用户列表给select2使用
	 * @param q  查询内容
	 * @param pageSize 每页大小
	 * @param currPage 当前页
	 * @return
	 */
	@RequestMapping("/userList")
	public @ResponseBody JSONObject userList(HttpServletRequest request, HttpServletResponse response, String q, Integer pageSize, Integer currPage) {
		if (AppUtils.isBlank(pageSize)) {
			pageSize = 50;
		}
		if (AppUtils.isBlank(currPage) || currPage <= 0) {
			currPage = 1;
		}
		return adminUserService.userList(q, pageSize, currPage);
	}

	/**
	 * 查询用户列表给select2使用, 查找我的团队下的成员
	 * @param q  查询内容
	 * @param pageSize 每页大小
	 * @param currPage 当前页
	 * @return
	 */
	@RequestMapping("/userListForMyColleague")
	public @ResponseBody JSONObject userListForMyColleague(HttpServletRequest request, HttpServletResponse response, String q, Integer pageSize, Integer currPage) {
		if (AppUtils.isBlank(pageSize)) {
			pageSize = 50;
		}
		if (AppUtils.isBlank(currPage) || currPage <= 0) {
			currPage = 1;
		}

		UserDetail userDetail = UserManager.getUser(request.getSession());

		String leaderName = userDetail.getUsername();
		boolean isAdmin = userDetail.hasFunction(FunctionEnum.FUNCTION_VIEW_ALL_DATA);//是否是数据管理员

		return adminUserService.userListForMyColleague(isAdmin, q, pageSize, currPage, leaderName);
	}
	
	/**
	 * 查询用户列表给select2使用，用户不在组里
	 * @param q  查询内容
	 * @param pageSize 每页大小
	 * @param currPage 当前页
	 * @return
	 */
	@RequestMapping("/userListForTeam/{projectId}")
	public @ResponseBody JSONObject userListForTeam(@PathVariable Long projectId, String q, Integer pageSize, Integer currPage) {
		if (AppUtils.isBlank(pageSize)) {
			pageSize = 300;
		}
		if (AppUtils.isBlank(currPage) || currPage <= 0) {
			currPage = 1;
		}
		return adminUserService.userListForTeam(projectId, q, pageSize, currPage);
	}
	
	/**
	 * 查询用户列表给select2使用
	 * @param q  查询内容
	 * @param pageSize 每页大小
	 * @param currPage 当前页
	 * @return
	 */
	@RequestMapping("/userListInTeam/{projectId}")
	public @ResponseBody JSONObject userListInTeam(@PathVariable Long projectId, String q, Integer pageSize, Integer currPage) {
		if (AppUtils.isBlank(pageSize)) {
			pageSize = 50;
		}
		if (AppUtils.isBlank(currPage) || currPage <= 0) {
			currPage = 1;
		}
		return adminUserService.userListInTeam(projectId, q, pageSize, currPage);
	}

}
